package com.tdam2011;

import java.io.ByteArrayInputStream;

import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.BasicHttpEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;
import org.xml.sax.InputSource;
import org.xml.sax.XMLReader;

import android.app.Activity;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

public class LoginServicioWeb extends Activity {
	private static final String TAG = "Login";
	String loginmessage = null;
	Button login;
	Thread t;
	ProgressDialog dialog;
    private SharedPreferences mPreferences; 
    
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.login_servicio_web);
		login = (Button) findViewById(R.id.btn_login);
		login.setOnClickListener(new View.OnClickListener() {
			 public void onClick(View view) {
				showDialog(0);
				tryLogin();
			}
		});
	}
	
	@Override
	protected Dialog onCreateDialog(int id) {
		switch (id) {
		case 0: {
			dialog = new ProgressDialog(this);
			dialog.setMessage("Conectado al sevidor para validar usuario...");
			dialog.setIndeterminate(true);
			dialog.setCancelable(true);
			return dialog;
		}
		}
		return null;
	}

	private Handler handler = new Handler() {
		@Override
		public void handleMessage(Message msg) {
			String loginmsg = (String) msg.obj;
			if (loginmsg.equals("SUCCESS")) {
				removeDialog(0);
				Intent intent = new Intent(getApplicationContext(),
						Contactos.class);
				startActivity(intent);
				finish();
			}
		}
	};

	public void tryLogin() {
		Log.v(TAG, "Trying to Login");
		EditText etxt_user = (EditText) findViewById(R.id.txt_nombre_usuario);
		EditText etxt_pass = (EditText) findViewById(R.id.txt_clave);
		String username = etxt_user.getText().toString();
		String password = etxt_pass.getText().toString();
		
/*		if(!txt_contraseniaUsuario.getText().toString().equals(txt_repContraseniaUsuario.getText().toString())){
			showDialog(ERROR_CONTRASENIA);
			return;
		}*/
		
		String xml=
			"<action id='REQUEST_RANDOM_VALUE' name='register-user'>" +
				"<action-detail>" +
					"<user username='"+username+"' password='"+password+"'/>" +
				"</action-detail>" +
			"</action>";
		try{
			HttpClient client = new DefaultHttpClient();
			HttpPost post = new HttpPost("http://127.0.0.1:8080/MessageSender/Sender");
			BasicHttpEntity ent = new BasicHttpEntity();
			ent.setContentType("application/xml");
			ByteArrayInputStream in = new ByteArrayInputStream(xml.getBytes());
			ent.setContent(in);
			post.setEntity(ent);						
			HttpResponse responsePost= client.execute(post);
			HttpEntity resEntity= responsePost.getEntity();
			
			SAXParser parser = XmlParserProvider.getParser(); 
			RegistroUsuarioHandler handler= new RegistroUsuarioHandler();
									
			if(resEntity != null){
				String res= EntityUtils.toString(resEntity);
				parser.parse(new ByteArrayInputStream(res.getBytes()), handler);
				XmlParserProvider.releaseParser(parser);
				if(handler.getRegitroOK()){
					// Guardo la preferencia
			        SharedPreferences app_preferences = getSharedPreferences("usuarioRegistrado", MODE_PRIVATE); 
			        SharedPreferences.Editor editor = app_preferences.edit();
			        editor.putInt("usuarioRegistrado", 1);
			        editor.putString("usuario", username);
			        editor.putString("contrasenia", password);
			        editor.commit();
			        
					setResult(RESULT_OK);
				}else
					Toast.makeText(this, handler.getMensaje(), Toast.LENGTH_LONG).show();
			}
			removeDialog(0);
		}catch (Exception e) {
			e.printStackTrace();
			Toast.makeText(this, "Error!!!", Toast.LENGTH_LONG).show();
		}
		removeDialog(0);		
	}

	private InputSource retrieveInputStream(HttpEntity httpEntity) {
		InputSource insrc = null;
		try {
			insrc = new InputSource(httpEntity.getContent());
		} catch (Exception e) {
		}
		return insrc;
	}

	// Checking whether the username and password has stored already or not
	private final boolean checkLoginInfo() {
		boolean username_set = mPreferences.contains("UserName");
		boolean password_set = mPreferences.contains("PassWord");
		if (username_set || password_set) {
			return true;
		}
		return false;
	}

}
